package com.woniu.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.entity.SysPermission;
import com.woniu.service.SysPermissionService;
import com.woniu.mapper.SysPermissionMapper;
import com.woniu.service.SysRolePermissionService;
import com.woniu.service.SysRoleService;
import com.woniu.util.ResponseData;
import com.woniu.util.easyExcelUtil.EasyExcelUtil;
import com.woniu.vo.RoleManagementVO;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * @author mashiro
 * @description 针对表【sys_permission(后台权限表)】的数据库操作Service实现
 * @createDate 2025-02-14 11:39:31
 */
@Service
@AllArgsConstructor
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission>
        implements SysPermissionService {
    private RedisTemplate<String, Object> redisTemplate;
    private SysRolePermissionService sysRolePermissionService;
    private SysRoleService sysRoleService;
    private SysPermissionMapper sysPermissionMapper;
    @Override
    public ResponseData<?> initPermission() {
        //mybaits-plus获取所有权限的id和permissionCode字段

        redisTemplate.delete("Permission");
        List<SysPermission> permissions = lambdaQuery().select(SysPermission::getId, SysPermission::getPermissionCode).list();
        //将权限信息存入redis
        permissions.forEach(permission -> {
            redisTemplate.opsForHash().put("Permission", permission.getId().toString(), permission.getPermissionCode());
        });
        return ResponseData.ok();
    }

    @Override
    public ResponseData<?> outPermissionExcel(HttpServletResponse response) throws IOException {
        List<SysPermission> permissions = lambdaQuery()
                .select(SysPermission::getId, SysPermission::getPermissionCode)
                .list();
        // 使用 EasyExcel 进行导出
        String fileName = UUID.randomUUID().toString();
        EasyExcelUtil.writeWithSheetsWeb(response, fileName)
                .writeModel(SysPermission.class, permissions, "sheetName1")
                .finish();
        return ResponseData.ok();
    }

    @Override
    public ResponseData<?> queryRoleList() {
        //查询角色信息
        List<RoleManagementVO> roleDTOS = sysPermissionMapper.queryRoleList();
//        将roleDTOS按roleId分组
        HashMap<String, List<RoleManagementVO>> roleMap = new HashMap<>();
        roleDTOS.forEach(roleManagementVO -> {
            roleMap.computeIfAbsent(roleManagementVO.getRoleId(), k -> new ArrayList<>()).add(roleManagementVO);
        });

        return ResponseData.ok(roleMap);
    }
}




